<template>
	<el-dialog
	  title="取样"
	  :visible.sync="visible"
	  :before-close="close"
	  :close-on-click-modal="false"
	  width="70%">
    注：此操作会记录在《取样台账记录》，并确认以下说明
    <el-tooltip effect="dark" :content="isFullLast ? '不填充' : '自动填充'" placement="top">
      <el-switch
        :disabled="fullLastDisabled"
        style="float: right;"
        v-model="isFullLast"
        @change="changeFullLast"
        active-color="#7cbd36"
        inactive-color="#ff4949"
        inactive-text="上一单">
      </el-switch>
    </el-tooltip>
	  <el-row style="margin-top: 5px;">
	    <el-col :span="24">
        <el-card>
          <el-form>
            <el-form-item
              v-for="(item, index) in dataList"
              :key="index"
              :prop="'dataList.' + index + 'getQuantity'">
              <span slot="label">
                确定接收 {{item.registCheckUserName}} 请验的样品<span class="font-highlight">【{{item.checkTypeName}}】{{item.productName}}（批号：{{item.batchNum}}<span v-if="item.productPackSpec != null">，包装规格：{{item.productPackSpec}}</span>）</span>
              </span>
              <el-input v-model="item.getQuantity" @change="changeGetQuantity(index)" placeholder="取样量(数值)">
                <el-select @change="setGetUnitByIndex(index)" value-key="unitId" v-model="item.getUnit" slot="append" placeholder="单位" style="width: 100px;">
                  <el-option v-for="item in unitList" :key="item.unitId" :label="item.unitName" :value="item" />
                </el-select>
              </el-input>
              <el-select style="width: 100%; margin-top: 10px;" @change="setSubdivideByIndex(index)" value-key="subdivideId" v-model="item.subdivide" placeholder="细分类别">
                <el-option v-for="item in subdivideList" :key="item.subdivideId" :label="item.subdivideName" :value="item" />
              </el-select>
              <el-input style="width: 100%; margin-top: 10px;" v-model="item.getRoom" placeholder="取样间" />
              <el-date-picker
                v-model="item.getDate"
                align="right"
                type="date"
                placeholder="取样日期"
                :clearable="false"
                style="width: 100%; margin-top: 10px;"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
	  </el-row>
	  <span slot="footer" class="dialog-footer">
	    <el-button @click="close">取 消</el-button>
      <el-button v-if="isReget" @click="submit" icon="el-icon-s-promotion" type="success" class="pan-btn success-btn">
        发送至{{ returnInfo.fromUserName }}
      </el-button>
	    <el-button class="pan-btn primary-btn" v-else type="primary" :loading="submiting" @click="submit">确 定</el-button>
  	</span>
	</el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { getUnitList,get,getLastCheckForGet,getSubdivideList } from '@/api/check'
	import { CODE_OK } from '@/common/js/config'
  import { isBlank,parseTime,dateCompare } from '@/common/js/utils'
  import { isOnlyPositiveNumber } from '@/common/js/validate'
	export default {
    name: 'quyang',
		data() {
			return {
				visible: false,
				fullLastDisabled: false,
				isFullLast: false,
				submiting: false,
				isReget: false,
				dataList: [],
				unitList: [],
        subdivideList: []
			}
		},
		props: ["childDataForm","returnInfo"],
		created() {
			if (!isBlank(this.childDataForm)) {
        this.init()
        let date = new Date()
        this.isReget = this.returnInfo == undefined ? false : true
        if (this.isReget) {
          this.fullLastDisabled = true
          this.dataList = this.childDataForm
          this.$set(this.dataList[0], 'getUnit', {
            unitId: this.dataList[0].getUnitId,
            unitName: this.dataList[0].getUnitName
          })
          this.$set(this.dataList[0], 'subdivide', {
            subdivideId: this.dataList[0].subdivideId,
            subdivideName: this.dataList[0].subdivideName
          })
        }else{
          this.dataList = this.childDataForm.map(item => {
            this.$set(item, 'subdivideId', '')
            this.$set(item, 'subdivideName', '')
            this.$set(item, 'getRoom', '')
            this.$set(item, 'getQuantity', '')
            this.$set(item, 'getUnitId', '')
            this.$set(item, 'getUnitName', '')
            this.$set(item, 'getUserId', this.userInfo.userId)
            this.$set(item, 'getUserName', this.userInfo.name)
            this.$set(item, 'getDate', parseTime(date))
            return item
          })
        }
        this.visible = true
			}
		},
    computed: {
      ...mapGetters([
         'userInfo'
      ])
    },
		methods: {
      init() {
        getUnitList().then(res => {
          if (res.code === CODE_OK) {
            this.unitList = res.list
          }else{
            this.$message.error(res.msg)
          }
        })
        getSubdivideList().then(res => {
          if (res.code === CODE_OK) {
            this.subdivideList = res.list
          }else{
            this.$message.error(res.msg)
          }
        })
      },
			close(val) {
				this.$emit('close')
        if (val == 'submit') {
          this.$emit('refreshData')
        }
				this.visible = false
			},
      changeFullLast() {
        if (this.isFullLast) {
          const checkIds = this.dataList.map(item => {
            return item.checkId
          })
          getLastCheckForGet(checkIds).then(res => {
            if (res.code === CODE_OK) {
              let getList = res.getList
              let listIds = this.dataList.map(item => {
                return item.checkId
              })
              let index = null
              for (let get of getList) {
                index = listIds.indexOf(get.checkId)
                this.dataList[index].getQuantity = get.getQuantity
                this.$set(this.dataList[index], 'getUnit', {
                  unitId: get.getUnitId,
                  unitName: get.getUnitName
                })
                this.$set(this.dataList[index], 'subdivide', {
                  subdivideId: get.subdivideId,
                  subdivideName: get.subdivideName
                })
                this.$set(this.dataList[index], 'getRoom', get.getRoom)
                this.setGetUnitByIndex(index)
                this.setSubdivideByIndex(index)
              }
            }else{
              this.$message.error(res.msg)
              this.isFullLast = false
            }
          })
        }else{
          //初始化

        }
      },
			submit() {
        if (!this.formVerify()) {
          return
        }
        this.submiting = true
        const data = {
          getList: this.isReget ? null : this.dataList,
          get: this.dataList[0],
          checkReturn: this.returnInfo
        }
        get(data).then(res => {
          if (res.code === CODE_OK) {
            this.$message({
              message: '提交成功',
              type: 'success',
              duration: 1500
            })
            this.close("submit")
          }else{
            this.submiting = false
            this.$message.error(res.msg)
          }
        })
			},
      formVerify() {
        for (let item of this.dataList) {
          if (isBlank(item.getQuantity) || isBlank(item.getUnitId) || isBlank(item.getUnitName)) {
            this.$message.error("所有取样量和单位均不能为空")
            return false
          }
          if (isBlank(item.getDate)) {
            this.$message.error("所有取样日期均不能为空")
            return false
          }
          // if (!dateCompare(item.registCheckDate, item.getDate)) {
          //   this.$message.error("所有取样日期必须晚于对应的请验日期")
          //   return false
          // }
        }
        return true
      },
      changeGetQuantity(index) {
        if (!isOnlyPositiveNumber(this.dataList[index].getQuantity)) {
          this.$message.error("取样量为正数")
          this.dataList[index].getQuantity = null
        }
      },
      setGetUnitByIndex(index) {
        this.dataList[index].getUnitId = this.dataList[index].getUnit.unitId
        this.dataList[index].getUnitName = this.dataList[index].getUnit.unitName
      },
      setSubdivideByIndex(index) {
        this.dataList[index].subdivideId = this.dataList[index].subdivide.subdivideId
        this.dataList[index].subdivideName = this.dataList[index].subdivide.subdivideName
      }
    }
	}
</script>

<style>
</style>
